1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| import random import re
humanTotalScore = 0 computerTotalScore = 0
def show_results(): global computerTotalScore global humanTotalScore
if computerTotalScore < humanTotalScore: print("You win by {} points.".format(humanTotalScore - computerTotalScore)) elif computerTotalScore > humanTotalScore: print("You lose by {} points.".format(computerTotalScore - humanTotalScore))
def roll_again(): return judge("Roll again?(y/n)")
def roll(): result = random.randint(1, 6) print("Current roll:", result) return result
def is_game_over(): global computerTotalScore global humanTotalScore return (computerTotalScore >= 50 or humanTotalScore >= 50) and computerTotalScore != humanTotalScore
def computer_move(): print("======Bot Turn======") global computerTotalScore if computerTotalScore >= 50: return
times = 4 turn_score = 0 while times > 0: current_roll = roll()
if current_roll == 6: turn_score = 0 break else: times = times - 1 turn_score += current_roll
computerTotalScore += turn_score print("Computer Score:", computerTotalScore)
def human_move(): print("======Your Turn======") global humanTotalScore global computerTotalScore
if humanTotalScore >= 50: return
print("Your Score: {}, Computer Score: {}, Distance: {}".format(humanTotalScore, computerTotalScore, humanTotalScore - computerTotalScore)) turn_score = 0
while True: if not roll_again(): break
current_score = roll()
if current_score == 6: return
turn_score += current_score
humanTotalScore += turn_score
def play_again(): global humanTotalScore global computerTotalScore
if not judge("Play again?(y/n)"): return False
humanTotalScore = 0 computerTotalScore = 0
return True
def judge(hint_str): while True: response = input(hint_str) if re.match('[yY].*', response) is not None: return True if re.match('[nN].*', response) is not None: return False
def instruction(): print("""Welcome to the game.You and the computer will take turns to roll a dice. Every figure, except 6, will be added to your score, and if you roll a 6, the score for this turn is 0, and another player will do it. The first player to reach or exceed 50 will win. """)
def main(): instruction() again_flag = True while again_flag: computer_move() human_move() if is_game_over(): show_results() again_flag = play_again()
main()
|